<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['id_send']) && isset($_POST['id_receive']) && isset($_POST['id_request'])) {
    
    $id_send = $_POST['id_send'];
    $id_receive = $_POST['id_receive'];
	$id_request = $_POST['id_request'];
$myArray = json_decode($id_receive, true);
    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();
    // mysql inserting a new row
	 foreach ($myArray as $key => $value) {

    $result = mysql_query("INSERT INTO message(id_send, id_receive, id_request) VALUES('$id_send', '$value', '$id_request')");
$id = mysql_insert_id();
echo $id;

}
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["responseCode"] = 1;
        $response["responseMessage"] = "Message successfully created.";

        //if insert message successfully -> push
            
            include_once './GCM.php';
            
            $gcm = new GCM();

			echo $value;
            //get regId

            if(mysql_query("SELECT gcm_regid FROM gcm_users WHERE name = '$value' limit 1"))
            {
            $regId = mysql_result(mysql_query("SELECT gcm_regid FROM gcm_users WHERE name = '$value' limit 1"),0);

            $registatoin_ids = array($regId);
            $message = array();
			$message['id'] = $id;
            $message['id_send'] = $id_send;
            $message['id_receive'] = $value;
            $message['id_request'] = $id_request;


            $result = $gcm->send_notification($registatoin_ids, $message);
        }
           // echo $result;
        


        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["responseCode"] = -1;
        $response["responseMessage"] = "Oops! An error occurred.";
        
        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["responseCode"] = -1;
    $response["responseMessage"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>